// 云函数入口文件
const cloud = require('wx-server-sdk')
const moment = require("moment")
const MAX_LIMIT = 100

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const db = cloud.database()
  const _ = db.command
  const userCount = await db.collection('user').where({
    isMember: true
  }).count()
  const userTotal = userCount.total
  // 计算需分几次取
  const userBatchTimes = Math.ceil(userTotal / 100)
  const userTasks = []
  for (let i = 0; i < userBatchTimes; i++) {
    const promise = db.collection('user').where({
      isMember: true,
      isOut: false
    }).orderBy('point', 'desc').skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
    userTasks.push(promise)
  }
  const userData = (await Promise.all(userTasks)).reduce((acc, cur) => {
    return {
      data: acc.data.concat(cur.data),
      errMsg: acc.errMsg,
    }
  })
  let userList = userData.data
  moment.locale('zh-cn');
  var m = moment().utcOffset(480)
  m.set({ hour: 0, minute: 0, second: 0, millisecond: 0 })
  const startWeekDate = m.week(moment().week()).startOf('week').valueOf();
  console.log("startWeekDate", startWeekDate)
  console.log(m.week(moment().week()).startOf('week').format('lll'))
  const endWeekDate = m.week(moment().week()).endOf('week').valueOf();
  console.log("endWeekDate", endWeekDate)
  console.log(m.week(moment().week()).endOf('week').format('lll'))

  for (var i = 0; i < userList.length; i++) {
    let user = userList[i]

    const weekCount = await db.collection('cards').where({
      _openid: user._openid,
      systemTime: _.lte(endWeekDate).and(_.gte(startWeekDate)),
    }).count()
    var weekPoints = [0, 0, 0, 0, 0, 0, 0]
    var totleWeekPoint = 0
    if (weekCount.total > 0) {
      const weekTotal = weekCount.total
      // 计算需分几次取
      const weekBatchTimes = Math.ceil(weekTotal / 100)
      const weekTasks = []
      for (let i = 0; i < weekBatchTimes; i++) {
        const promise = db.collection('cards').where({
          _openid: user._openid,
          systemTime: _.lte(endWeekDate).and(_.gte(startWeekDate)),
        }).skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
        weekTasks.push(promise)
      }
      const weekCards = (await Promise.all(weekTasks)).reduce((acc, cur) => {
        return {
          data: acc.data.concat(cur.data),
          errMsg: acc.errMsg,
        }
      })
      let cardList = weekCards.data;
      for (var j = 0; j < cardList.length; j++) {
        let card = cardList[j]
        if (card.status == 'checked') {
          weekPoints[card.type.index] = weekPoints[card.type.index] + card.point
        }
      }
      for (var k = 0; k < weekPoints.length-1; k++) {
        totleWeekPoint = parseInt(totleWeekPoint) + parseInt(weekPoints[k])
      }
    }
    db.collection('user').where({
      _openid: user._openid,
    }).update({
      data: {
        weekPoint: totleWeekPoint
      }
    })
  }
  return {
    event,
    openid: wxContext.OPENID,
    appid: wxContext.APPID,
    unionid: wxContext.UNIONID,
  }
}